package pers.lolicer.redtidelibrary.pages

import android.annotation.SuppressLint
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.HorizontalDivider
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import pers.lolicer.redtidelibrary.R
import pers.lolicer.redtidelibrary.components.BookList
import pers.lolicer.redtidelibrary.components.BookNavigation
import pers.lolicer.redtidelibrary.components.TopBar
import pers.lolicer.redtidelibrary.repository.MyDatabase
import pers.lolicer.redtidelibrary.repository.entity.BookEntity


@SuppressLint("CoroutineCreationDuringComposition")
@Composable
fun MainPage(navController: NavController) {
    val context = LocalContext.current
    val bookDao = MyDatabase.getDB(context).getBookDao()


    val isDataSync = remember { mutableStateOf(false) }
    val isContentVisible = remember {mutableStateOf(true)}

    val foldersSet: MutableSet<String> = mutableSetOf()
    val allBooks = remember { mutableStateOf(listOf<BookEntity>()) }

    val sortMethod = remember { mutableIntStateOf(R.integer.sortMethod_time_last_open) }
    val folderFilter = remember { mutableStateOf("") }
    val searchFilter = remember { mutableStateOf("") }

    if(!isDataSync.value){
        isDataSync.value = true

        CoroutineScope(Dispatchers.IO).launch{
            val mid = bookDao.getAll()
            withContext(Dispatchers.Main){
                allBooks.value = mid
            }
            // Log.d("Update Data From Room", allBooks.value.toString())
        }
    }
    allBooks.value.forEach { entity ->
        foldersSet.add(entity.folder)
    }

    BackHandler(enabled = !isContentVisible.value) {
        isContentVisible.value = true // 返回时重新显示 PageA 的内容
    }

    if(isContentVisible.value){
        Column(modifier = Modifier.navigationBarsPadding().background(AppColor.Background(context))){
            TopBar(isDataSync, searchFilter, navController, isContentVisible)
            HorizontalDivider(thickness = 2.dp, modifier = Modifier.padding(4.dp))
            BookNavigation(sortMethod, foldersSet.toSet(), folderFilter)
            HorizontalDivider(thickness = 2.dp, modifier = Modifier.padding(4.dp))
            BookList(allBooks.value, sortMethod.intValue, foldersSet.toSet(), folderFilter.value, searchFilter.value, isDataSync)
        }
    }
}